package com.xmut.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmut.eduservice.entity.EduSubject;
import com.xmut.eduservice.entity.excel.ExcelSubjectData;
import com.xmut.eduservice.service.EduSubjectService;

public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    // 因为SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }


    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if (excelSubjectData == null) {
            throw new NullPointerException("excelSubjectData为空");
        }
        // 一行一行读取，每次有两个值，第一个值一级分类，第二个值二级分类

        // 如果表里面没有相同的一级分类
        EduSubject eduSubjectOne = this.existSubject(eduSubjectService, excelSubjectData.getOneSubjectName(), "0");
        if(eduSubjectOne == null) {
            eduSubjectOne = new EduSubject();
            eduSubjectOne.setParentId("0");
            eduSubjectOne.setTitle(excelSubjectData.getOneSubjectName());
            eduSubjectService.save(eduSubjectOne);
        }
        EduSubject eduSubjectTwo = this.existSubject(eduSubjectService, excelSubjectData.getTwoSubjectName(), eduSubjectOne.getId());
        // 如果表里面没有相同的二级分类
        if(eduSubjectTwo == null) {
            eduSubjectTwo = new EduSubject();
            eduSubjectTwo.setParentId(eduSubjectOne.getId());
            eduSubjectTwo.setTitle(excelSubjectData.getTwoSubjectName());
            eduSubjectService.save(eduSubjectTwo);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    // 判断分类不能重复添加
    private EduSubject existSubject(EduSubjectService eduSubjectService, String name, String pid) {
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", name);
        queryWrapper.eq("parent_id", pid);
        EduSubject eduSubject = eduSubjectService.getOne(queryWrapper);
        return eduSubject;
    }
}
